package org.dromara.assets.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.dromara.system.domain.AssetsMytokenactionrecord;
import org.dromara.system.service.IAssetsMytokenactionrecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.*;

@Component("assetsTask")
@Slf4j
public class Task {

    List<Integer> bandTypes = Arrays.asList(0, 1, 2);

    List<String> symbols = Arrays.asList("btc", "eth");

    @Autowired
    IAssetsMytokenactionrecordService assetsMytokenactionrecordService;

    public void task() throws Exception {
        List<String> items = new ArrayList<>();
        for (Integer bandType : bandTypes) {
            for (String symbol : symbols) {
                Result1 result = getAction(symbol, bandType);
                Result1.Result.FormattedAddress latestItem = result.getData().getList().get(0);
                latestItem.setTrading_at(latestItem.getTrading_at() * 1000);
                boolean isExist = isExistInDb(latestItem, symbol, bandType);
                if (!isExist) {
                    String timeStr = DateUtil.formatDateTime(new Date(latestItem.getTrading_at())) ;
                    String noticeStr = symbol + " " + latestItem.getAction() + " " + getBandTypeCname(bandType) +
                            " " + timeStr + " " + NumberUtil.decimalFormat("#.###", latestItem.getPrice()) + " " + NumberUtil.decimalFormat("#.###", latestItem.getRatio());
                    items.add(noticeStr);
                    save2db(latestItem, symbol, bandType);
                }

            }
        }
        send_email(items);
    }


    public boolean isExistInDb(Result1.Result.FormattedAddress latestItem, String symbol, Integer bandType) {
        AssetsMytokenactionrecord assetsMytokenactionrecord = new AssetsMytokenactionrecord();

        assetsMytokenactionrecord.setTradingAt(new Date(latestItem.getTrading_at()));
        assetsMytokenactionrecord.setSymbol(symbol);
        assetsMytokenactionrecord.setBandType(Long.parseLong(bandType + ""));
        List<AssetsMytokenactionrecord> result = assetsMytokenactionrecordService.selectAssetsMytokenactionrecordList(assetsMytokenactionrecord);
        if (CollectionUtils.isNotEmpty(result)) {
            return true;
        }
        return false;

    }


    public void save2db(Result1.Result.FormattedAddress latestItem, String symbol, Integer bandType) {
        AssetsMytokenactionrecord assetsMytokenactionrecord = new AssetsMytokenactionrecord();
        assetsMytokenactionrecord.setAction(latestItem.getAction());
        assetsMytokenactionrecord.setSymbol(symbol);
        assetsMytokenactionrecord.setBandType(Long.parseLong(bandType + ""));
        assetsMytokenactionrecord.setPrice(BigDecimal.valueOf(latestItem.getPrice()));
        assetsMytokenactionrecord.setRatio(BigDecimal.valueOf(latestItem.getRatio()));
        assetsMytokenactionrecord.setTradingAt(new Date(latestItem.getTrading_at()));
        assetsMytokenactionrecord.setUpdateTime(new Date());
        assetsMytokenactionrecord.setComment("");
        assetsMytokenactionrecordService.insertAssetsMytokenactionrecord(assetsMytokenactionrecord);

        //MytokenActionRecord.objects.create(action = latestItem["action"], symbol = symbol, band_type = band_type,
        //        price = round(float
        //(latestItem["price"]), 4),
        //ratio =float
        //('%.4f' % latestItem["ratio"]), trading_at = datetime.datetime.fromtimestamp(latestItem["trading_at"], None)
        //    )
    }

    public static Result1 getAction(String symbol, int bandType) throws Exception {

        final String url = "https://api.mytokenapi.com/band/tradinghistorylist?udid=mytoken_user&symbol=" + symbol +
                "&anchor=usdt&page=1&size=20&band_type=" + bandType + "&language=zh_CN&legal_currency=USD&trade_style=3" +
                "&timestamp=1673871075799&code=822f9500c78f22005a7aab8f4fcecfe8&platform=web_pc&v=0.1.0&mytoken=07d27df8bfff44410a99bb090b8c3785&international=1";
        HttpHeaders requestHeaders = new HttpHeaders();

        requestHeaders.add("authority", "api.mytokenapi.com");
        requestHeaders.add("pragma", "no-cache");
        requestHeaders.add("cache-control", "no-cache");
        requestHeaders.add("sec-ch-ua", "\"Google Chrome\";v=\"89\", \"Chromium\";v=\"89\", \";Not A Brand\";v=\"99\"");
        requestHeaders.add("accept", "application/json, text/plain, */*");
        requestHeaders.add("sec-ch-ua-mobile", "?0");
        requestHeaders.add("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 12_0_1) AppleWebKit/537.36 (KHTML, " + "like Gecko) Chrome/89.0.4389.90 Safari/537.36");
        requestHeaders.add("content-type", "application/x-www-form-urlencoded;charset=utf-8");
        requestHeaders.add("origin", "https://www.mytokencap.com");
        requestHeaders.add("sec-fetch-site", "cross-site");
        requestHeaders.add("sec-fetch-mode", "cors");
        requestHeaders.add("sec-fetch-dest", "empty");
        requestHeaders.add("referer", "https://www.mytokencap.com/");
        requestHeaders.add("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7,ja;q=0.6,en-ZA;q=0.5");

        Map<String, String> param = new HashMap<>();
        param.put("symbol", symbol);
        param.put("anchor", "usdt");
        param.put("page", "1");
        param.put("size", "40");
        param.put("band_type", bandType + "");
        param.put("language", "zh_CN");
        param.put("trade_style", "1");
        param.put("timestamp", "1581867320266");
        param.put("code", "19f5f3e7c3e46e4ab903091f8d129ac4");
        param.put("platform", "web_app");


        RestTemplate template = new RestTemplate();
        HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);

        ResponseEntity<String> response1 = template.exchange(url, HttpMethod.GET, requestEntity, String.class);
        System.out.println(response1.getBody().toString());
        ObjectMapper mapper = new ObjectMapper();
        Result1 dd = mapper.readValue(response1.getBody().toString(), Result1.class);

        if (1 == 1) {
            return dd;
        }
        template = restTemplate();

        ResponseEntity<Result1> response = template.exchange(url, HttpMethod.GET, requestEntity, Result1.class);
        Result1 sttr = response.getBody();
        System.out.println(sttr.toString());
        return dd;
    }


    public static ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
        mapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper;
    }

    public static MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(objectMapper());
        return converter;
    }

    public static RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(0, mappingJacksonHttpMessageConverter());
        return restTemplate;
    }

    public static void main(String[] args) throws Exception {
        DigestUtil.md5Hex("陈啟福、王国芳");

        getAction("", 1);
    }


    public void send_email(List<String> items) {

        if (CollectionUtils.isEmpty(items)) {
            return;
        } else {
            log.info("begin to send email");
            String sender = "12144509@qq.com";
            List<String> receivers = Arrays.asList("8607071@qq.com");
            String subject = "MyToken有新的操作";
            String content = "<html>";
            for (String i : items) {
                content += i + "<br>";
                content += "</html>";
            }
            Map<String, Object> parms = new HashMap<>();
            parms.put("host", "smtp.qq.com");
            parms.put("port", 465);

            parms.put("from", sender);
            parms.put("user", sender);
            parms.put("pass", "hyoxksspsvlxbijc");

            sendHtmlEmail(parms, receivers, subject, content);

        }


    }

    public String getBandTypeCname(Integer bandType) {
        String result = "";
        if (bandType == 0) {
            result = "短线";
        } else if (bandType == 1) {
            result = "中线";
        } else if (bandType == 2) {
            result = "长线";
        } else {
            result = "未知的类型";
        }
        return result;
    }


    /**
     * 发送HTML邮件
     *
     * @param parms     邮件配置参数
     * @param adressees 收件人列表
     * @param title     邮件标题
     * @param html      邮件内容
     * @return 是否成功
     */
    public static boolean sendHtmlEmail(Map<String, Object> parms, List<String> adressees, String title, String html) {
        boolean flag = true;
        try {
            MailAccount account = new MailAccount();
            account.setHost((String) parms.get("host"));
            account.setPort((Integer) parms.get("port"));
            account.setAuth(true);
            account.setFrom((String) parms.get("from"));
            account.setUser((String) parms.get("user"));
            account.setPass((String) parms.get("pass"));
            // 使用SSL安全连接
            account.setSslEnable(true);
            //指定实现javax.net.SocketFactory接口的类的名称,这个类将被用于创建SMTP的套接字
            account.setSocketFactoryClass("javax.net.ssl.SSLSocketFactory");
            //如果设置为true,未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类, 默认值为true
            account.setSocketFactoryFallback(true);
            // 指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口456
            account.setSocketFactoryPort(465);
            MailUtil.send(account, adressees, title, html, true);
        } catch (Exception e) {
            log.error("邮件发送异常", e);
            flag = false;
        }
        log.info("邮件发送状态：{}", flag ? "发送成功" : "发送失败");
        return flag;
    }
}
